package com.totoro.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.totoro.domain.Department;
import com.totoro.service.DepartmentService;
import com.totoro.service.SchoolService;
import com.totoro.util.CommonConstant;
import com.totoro.util.Page;

@Controller
@RequestMapping("/department")
public class DepartmentController {

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private SchoolService schoolService;

	@RequestMapping("/list")
	public ModelAndView list(Integer pageNo) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/department/list");
		
		pageNo = pageNo == null ? 1 : pageNo;
		Page<Department> pagedPost = departmentService.getPagePosts(pageNo,
				CommonConstant.PAGE_SIZE);
		
		mav.addObject("pagedPost", pagedPost);
		mav.addObject("departmentList", pagedPost.getResult());
		mav.addObject("pageNo", pageNo);
		return mav;
	}

	@RequestMapping("/findByName")
	public ModelAndView findByName(String description) {
		System.out.println("description: " + description);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/department/list");
		mav.addObject("departmentList",
				departmentService.list("description", new String(description)));
		return mav;
	}

	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public String toSave(ModelMap modelMap) {
		modelMap.addAttribute("department", new Department());
		modelMap.addAttribute("schoolList", schoolService.list());
		return "/department/save";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@ModelAttribute("department") Department department) {
		System.out.println("department: " + department);
		departmentService.save(department);
		return "redirect:/department/list.html";
	}

	@RequestMapping("/findById/{id}")
	public String findById(@PathVariable("id") Integer id, ModelMap modelMap) {
		modelMap.addAttribute("schoolList", schoolService.list());
		modelMap.addAttribute("department", departmentService.get(id));
		return "/department/update";
	}

	@RequestMapping("/update")
	public String update(@ModelAttribute("department") Department department) {
		System.out.println(department);
		departmentService.update(department);
		return "redirect:/department/list.html";
	}

	@RequestMapping("/delete/{id}")
	public String delete(Department department) {
		departmentService.deleteObject(department);
		return "redirect:/department/list.html";
	}

}
